'''
Created on Sep 3, 2011

@author: david
'''
from google.appengine.ext import db
import logging
from datetime import datetime
import simplejson as json
from app.G6 import DATE_TIME_FMT


class Account(db.Model):
    # properties
    name = db.StringProperty()
    uid = db.EmailProperty()
    pwd = db.StringProperty()
    status = db.IntegerProperty()
    dt_open = db.DateTimeProperty(auto_now_add = True)
    dt_last = db.DateTimeProperty(auto_now_add = True)
    aid = db.StringProperty()
    
    def toJSON(self, asText=True):
        """
        Utility to help with conversion to JSON
        """
        opened = self.dt_open or datetime.now()
        last = self.dt_last or datetime.now()
        if asText:
            opened = opened.strftime(DATE_TIME_FMT)
            last = last.strftime(DATE_TIME_FMT)
            logging.debug("~~ Opened: %s" % opened)
        
        np = "::"
        if self.name:
            np = self.name.split(np)
            
        return json.dumps({ "fname":np[0],"lname":np[1],
                            "uid":self.uid,"pwd":self.pwd,
                            "opened": opened,"last":last, 
                            "aid": self.aid  
                           })
        
class Blog(db.Model):
    name = db.StringProperty()
    description = db.StringProperty()
    dt_create = db.DateTimeProperty(auto_now_add = True)
    dt_last = db.DateTimeProperty(auto_now_add = True)
    tags = db.StringProperty(multiline=True)
    default = db.BooleanProperty(default=False)
    url = db.StringProperty()
    bid = db.StringProperty()
    
    def toJSON(self, asText=True):
        created = self.dt_create or datetime.now()
        last = self.dt_last or datetime.now()
        dflt = self.default
        
        if asText:
            created = created.strftime(DATE_TIME_FMT)
            last = last.strftime(DATE_TIME_FMT)
            dflt = str(dflt)
            
        return json.dumps({ "name": self.name,"description":self.description,
                            "created": created, "last": last,
                            "tags": self.tags, "default": dflt,
                            "url": self.url, "bid": self.bid })
        
class Article(db.Model):
    subj = db.StringProperty()
    text = db.StringProperty(multiline=True)
    tags = db.StringProperty(multiline=True)
    tmstmp = db.DateTimeProperty(auto_now_add = True)
    aid = db.StringProperty()
    
    def toJSON(self, asText=True):
        tmstmp = self.tmstmp or datetime.now()
        if asText:
            tmstmp = tmstmp.strftime(DATE_TIME_FMT)
        
        return json.dumps({"subj":self.subj, "text": self.text,
                           "tags":self.tags,"tmstmp":tmstmp, "aid": self.aid })
        
        